import os
from PySide6.QtWidgets import (QTableWidget, QAbstractItemView, QHeaderView,
                             QTableWidgetItem, QMessageBox, QPushButton, QWidget, QHBoxLayout)
from PySide6.QtCore import Qt, QUrl, Signal
from PySide6.QtGui import QColor, QBrush
from src.ui.i18n import _
from src.utils.formatter import format_seconds

class VideoTableWidget(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptDrops(True)
        self.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.setAlternatingRowColors(True)
        self.setSortingEnabled(True)

        self.setup_columns()

    def setup_columns(self):
        self.setColumnCount(4)
        self.setHorizontalHeaderLabels([
            _("#"), _("File Name"), _("Status"), _("Elapsed Time")
        ])
        
        # Set header resizing behavior
        header = self.horizontalHeader()
        header.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        header.setSectionResizeMode(2, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(3, QHeaderView.ResizeToContents)
        
        self.verticalHeader().setVisible(False)
        self.setColumnWidth(0, 40)
        self.setColumnWidth(2, 120)
        self.setColumnWidth(3, 100)

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls():
            event.acceptProposedAction()
        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasUrls():
            urls = event.mimeData().urls()
            video_files = []
            for url in urls:
                if url.isLocalFile():
                    path = url.toLocalFile()
                    if path.lower().endswith(('.mp4', '.mkv', '.mov', '.avi', '.flv')):
                        video_files.append(path)
                    else:
                        self.show_warning(_("Unsupported File"), _("Only video files are supported. Skipped: {}").format(os.path.basename(path)))
            
            if video_files:
                self.add_videos(video_files)
            event.acceptProposedAction()
        else:
            event.ignore()

    def add_videos(self, file_paths):
        # Prevent adding duplicate files
        existing_paths = set(self.get_all_file_paths())
        
        for file_path in file_paths:
            if file_path in existing_paths:
                continue

            row_position = self.rowCount()
            self.insertRow(row_position)

            # Column 0: Index (Numeric)
            index_item = QTableWidgetItem()
            index_item.setData(Qt.DisplayRole, row_position + 1)
            index_item.setTextAlignment(Qt.AlignCenter)
            self.setItem(row_position, 0, index_item)

            # Column 1: File Name
            file_name_item = QTableWidgetItem(os.path.basename(file_path))
            file_name_item.setData(Qt.UserRole, file_path) # Store full path
            self.setItem(row_position, 1, file_name_item)

            # Column 2: Status
            status_item = QTableWidgetItem(_("Pending"))
            status_item.setTextAlignment(Qt.AlignCenter)
            self.setItem(row_position, 2, status_item)

            # Column 3: Elapsed Time
            time_item = QTableWidgetItem("0.0s")
            time_item.setTextAlignment(Qt.AlignCenter)
            self.setItem(row_position, 3, time_item)

            # Add the new path to the set to avoid duplicates within the same batch
            existing_paths.add(file_path)

    def update_status(self, row, status, is_error=False):
        item = self.item(row, 2)
        if item:
            item.setText(status)
        
        self._update_row_highlight(row, is_error)

    def _update_row_highlight(self, row, is_error):
        """Sets or clears the background color for a row based on error state."""
        color = QColor(255, 200, 200) if is_error else QColor(Qt.transparent)
        
        for column in range(self.columnCount()):
            item = self.item(row, column)
            if item:
                item.setBackground(color)

    def update_time(self, row, elapsed_seconds):
        item = self.item(row, 3)
        if item:
            item.setText(format_seconds(elapsed_seconds))
            
    def get_selected_rows(self):
        return sorted([index.row() for index in self.selectionModel().selectedRows()])

    def get_file_path(self, row):
        item = self.item(row, 1)
        return item.data(Qt.UserRole) if item else None

    def get_all_file_paths(self):
        return [self.get_file_path(row) for row in range(self.rowCount())]

    def remove_rows(self, rows):
        # Sort rows in descending order to avoid index shifting issues
        for row in sorted(rows, reverse=True):
            self.removeRow(row)
        # Re-number the index column
        for row in range(self.rowCount()):
            self.item(row, 0).setData(Qt.DisplayRole, row + 1)

    def clear_list(self):
        self.setRowCount(0)

    def show_warning(self, title, message):
        QMessageBox.warning(self, title, message)
